<template>
  <div class="drawer">
    <el-drawer :title="title"
               :visible.sync="drawerVisible"
               :size="size"
               :direction="direction"
               :with-header="true"
               @close="handleClose">
      <div class="drawer_content">
        <!-- 使用 el-row 和 el-col 进行布局 -->
        <el-row :gutter="10">
          <!-- 左侧部分放置表格 -->
          <div class="table-container">
            <el-col :span="14">
              <el-input class="table-input"
                        placeholder="请输入商品名称查询"
                        v-model="queryData.productName">
                <template slot="prepend"><i class="el-icon-search"></i></template>
                <el-button slot="append"
                           @click="getList">查询</el-button>
              </el-input>
              <el-table :data="tableData"
                        style="width: 100%;"
                        border
                        stripe>
                <el-table-column prop="productName"
                                 label="商品"
                                 align="center"
                                 header-align="center"
                                 min-width="60px"></el-table-column>

                <el-table-column label="单价"
                                 align="center"
                                 header-align="center"
                                 min-width="80px"
                                 style="overflow: visible;">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.salePrice"
                                     :min="0"
                                     :step="0.01"
                                     size="small"
                                     @change="handleQuantityChange(scope.row)"></el-input-number>
                  </template>
                </el-table-column>

                <el-table-column label="数量"
                                 align="center"
                                 header-align="center"
                                 min-width="80px"
                                 style="overflow: visible;">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.quantity"
                                     :min="1"
                                     size="small"
                                     @change="handleQuantityChange(scope.row)">
                    </el-input-number>
                  </template>
                </el-table-column>

                <el-table-column label="金额"
                                 align="center"
                                 header-align="center"
                                 min-width="60px">
                  <template slot-scope="scope">
                    {{ (scope.row.salePrice * scope.row.quantity).toFixed(2) }}
                  </template>
                </el-table-column>

                <el-table-column label="操作"
                                 align="center"
                                 header-align="center"
                                 min-width="60px">
                  <template slot-scope="scope">
                    <el-button type="text"
                               @click="deleteItem(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </div>

          <!-- 右侧部分放置 tabs 标签页 -->
          <div class="container">
            <el-col :span="10">
              <el-tabs tab-position="right"
                       v-model="activeTab">
                <el-tab-pane v-for="(option, index) in categoryIdOptions"
                             :key="index"
                             :label="option.label"
                             :name="option.value">
                  <div class="consCard">
                    <el-row :gutter="0">
                      <el-col :span="12"
                              v-for="item in filteredTabsData(option.value)"
                              :key="item.id">
                        <el-card class="product-card"
                                 @click.native="addCommodity(item)">
                          <p class="card-title">{{ item.productName }}</p>
                          <div class="card-details">
                            <div class="card-info">
                              <span class="card-price">￥{{ item.salePrice }}</span>
                              <span class="card-stock">库存：{{ item.stockQuantity }}</span>
                            </div>
                            <div class="card-image">
                              <img src="../../../static/Shoop.png"
                                   alt="商品图片">
                            </div>
                          </div>
                        </el-card>
                      </el-col>
                    </el-row>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </div>
        </el-row>
        <!-- 底部按钮 -->
        <div class="bottom-button">
          <div class="bottom-button-text">
            <span style="font-weight: bold;">
              <span style="color: red;">
                {{ totalQuantity }}
              </span> 件 合计
              <span style="color: red; font-size: 20px;">
                {{ totalPrice }}
              </span> 元
            </span>
          </div>
          <el-button type="primary"
                     icon="el-icon-check"
                     @click="completeOrder">点单完成</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  props: {
    title: String,
    tableInfo: Object,
    size: {
      type: String,
      default: '30%',
    },
    direction: {
      type: String,
      default: 'rtl',
    },
  },
  data() {
    return {
      drawerVisible: false,
      direction: 'rtl', // 设置抽屉方向为从右到左
      tableData: [],
      tabsData: [],
      addList: [],
      totalQuantity: 0,
      totalPrice: 0,
      activeTab: 'all', // 设置默认选项为"全部商品"
      categoryIdOptions: [{ label: '全部商品', value: 'all' }],
      originalCategoryIdOptions: [{ label: '全部商品', value: 'all' }], // 保存初始值
      selectedItem: null,
      queryData: {
        productName: '',
      },
    };
  },
  methods: {
    toggleDrawer() {
      this.getProductCategory();
      this.getList();
      this.drawerVisible = !this.drawerVisible;
    },
    closeDrawer() {
      this.clearData();
      this.drawerVisible = false;
      this.categoryIdOptions = this.originalCategoryIdOptions;
      this.totalQuantity = 0;
      this.totalPrice = 0;
    },
    clearData() {
      this.tableData = [];
      this.selectedItem = null;
      this.addList = [];
    },
    handleClose() {
      this.$emit('close');
    },
    async getList() {
      let res = await this.$api.productInfoApi.all(this.queryData, {
        loadingTime: 100,
        loadingText: '数据加载中...',
      });
      if (res) {
        this.tabsData = res;
      }
    },
    async getProductCategory() {
      let res = await this.$api.productCategoryApi.getSelect(
        {},
        {
          loadingTime: 100,
          loadingText: '数据加载中...',
        }
      );
      if (res) {
        // 在获取数据后手动添加"全部商品"选项
        this.categoryIdOptions = [...this.categoryIdOptions, ...res];
        this.activeTab = 'all'; // 设置初始选项为"全部商品"
      }
    },
    filteredTabsData(categoryValue) {
      if (categoryValue === 'all') {
        return this.tabsData; // 返回所有数据
      } else {
        return this.tabsData.filter(
          (item) => item.categoryId === categoryValue
        );
      }
    },
    /**
     * 添加商品
     */
    addCommodity(value) {
      let existingProduct = this.tableData.find(
        (item) => item.productName === value.productName
      );
      if (existingProduct) {
        // 商品已存在，增加数量和更新价格
        existingProduct.quantity += 1;
        existingProduct.price += value.salePrice;
      } else {
        // 商品不存在，添加新商品
        let newItem = {
          productName: value.productName,
          salePrice: value.salePrice,
          stockQuantity: value.stockQuantity,
          quantity: 1,
          price: value.salePrice,
        };
        this.tableData.push(newItem);
      }
      let backProduct = this.addList.find(
        (item) => item.commodityName === value.productName
      );
      if (backProduct) {
        backProduct.quantity += 1;
        backProduct.totalAmount += value.salePrice;
      } else {
        // 将 value 添加到 addList 中
        let backendItem = {
          // 假设这里根据后台数据接口的定义进行赋值
          commodityId: value.id, // 后台使用 commodityName 字段
          commodityName: value.productName, // 后台使用 commodityName 字段
          unitPrice: value.salePrice, // 假设后台使用 unitPrice 字段
          quantity: 1,
          totalAmount: value.salePrice, // 假设后台使用 totalAmount 字段
          status: 0, // 假设默认为正常状态
          uuid: this.tableInfo.uuid, // 假设后台使用 uuid 字段
        };
        this.addList.push(backendItem);
      }
      // 更新总数和合计金额
      this.totalQuantity += 1;
      this.totalPrice += value.salePrice;
    },
    handleQuantityChange(row) {
      // 找到对应的商品
      const updatedProduct = this.tableData.find(
        (item) => item.productName === row.productName
      );

      if (updatedProduct) {
        // 更新商品的数量和价格（quantity * salePrice）
        updatedProduct.quantity = row.quantity;
        updatedProduct.price =
          updatedProduct.quantity * updatedProduct.salePrice;

        // 更新总数量和总金额
        this.totalQuantity = this.tableData.reduce(
          (total, item) => total + item.quantity,
          0
        );

        this.totalPrice = this.tableData.reduce(
          (total, item) => total + item.price,
          0
        );
      }

      // 更新 addList
      const updateItem = this.addList.find(
        (item) => item.commodityName === row.productName
      );

      if (updateItem) {
        updateItem.quantity = row.quantity;
        updateItem.unitPrice = row.salePrice;
        updateItem.totalAmount = updateItem.quantity * row.salePrice;
      }
    },
    async completeOrder() {
      let res = await this.$api.commodityApi.addList(this.addList, {
        loadingTime: 100,
        loadingText: '数据加载中...',
      });
      if (res) {
        this.closeDrawer();
        this.$message({
          type: 'success',
          message: '商品下单成功!',
        });
      }
    },
  },
};
</script>
<style scoped lang="less">
@import '../../styles/consumption.css';
</style>